#pragma once
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

#define LOG_TXT "./log/log.txt"
static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;

#define INF 0
#define DBG 1
#define ERR 2
#define LOG_LEVEL DBG
#define LOG(level,format,...) do{\
        if(level < LOG_LEVEL) break;\
        pthread_mutex_lock(&log_mutex);\
        FILE *fp = fopen(LOG_TXT, "a+");\
        if (fp == NULL) { \
            pthread_mutex_unlock(&log_mutex);\
            break; \
        }\
        time_t t = time(NULL);\
        struct tm *ltm = localtime(&t);\
        char tmp[32] = {0};\
        strftime(tmp,31,"%H:%M:%S",ltm);\
        fprintf(fp,"[%p %s %s:%d]" format "\n",(void*)pthread_self(),\
                tmp,__FILE__,__LINE__,##__VA_ARGS__);\
        fclose(fp);\
        pthread_mutex_unlock(&log_mutex);\
    }while(0)  

#define INF_LOG(format,...) LOG(INF,format"\n",##__VA_ARGS__)
#define DBG_LOG(format,...) LOG(DBG,format"\n",##__VA_ARGS__)
#define ERR_LOG(format,...) LOG(ERR,format"\n",##__VA_ARGS__)
